package com.wg.io.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.wg.io.Resources;
import com.wg.io.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author Mrwg
 * @date 2020/3/26 12:08
 * @description 解析数据库配置文件，封装到configuration
 */
public class XMLConfigerBuilder {
    private Configuration configuration;

    public XMLConfigerBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    // 使用dom4j 解析输入的值结束输入流
    public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        //configuration
        Element rootElement = document.getRootElement();
        //    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        List<Element> propertyElements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }
        //链接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //封装到configuration
        configuration.setDataSource(comboPooledDataSource);
        ///mapper部分
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            InputStream resourceSteam = Resources.getResourceAsSteam(mapperPath);
            xmlMapperBuilder.parse(resourceSteam);
        }
        return configuration;

    }

}
